<?php

namespace Muyuxuanpay\threePay\src\cj\jsPayment;

use Muyuxuanpay\pay\common\Tool;
use Muyuxuanpay\threePay\BaseTrait;
use Muyuxuanpay\threePay\JsPayment;
use Muyuxuanpay\threePay\src\cj\CommonTrait;
use Muyuxuanpay\tool\Mtool;

class Pay implements JsPayment
{
    use BaseTrait;
    use CommonTrait;
    protected $typeList = [
        'wechat'
    ];
    protected $defaultConfig = [
        'format'=>'JSON',
        'charset'=>'UTF-8',
        'sign_type'=>'RSA2',
        'version'=>'1.0',
    ];
    public function pay(string $type,string $out_trade_no,$total_amount,string $body,string $appid,string $openid,array $event=[])
    {
        $type = strtolower($type);
        if(!in_array($type,$this->typeList)){
            throw new \Exception('不支持的支付方式');
        }
        // 验证
        $this->verify();
        if($type==='wechat'){
            return $this->wechat($out_trade_no,$total_amount,$body,$appid,$openid,$event);
        }
    }
    protected function wechat(string $out_trade_no,$total_amount,string $body,string $appid,string $openid,array $event=[])
    {
        $now = date('YmdHis');
        $msgCiphertext = [
            'out_trade_no'=>$out_trade_no,
            'total_amount'=>intval($total_amount*100),
            'body'=>$body,
            'mch_create_ip'=>$this->getClientIp(),
            'sub_openid'=>$openid,
            'sub_appid'=>$appid,
        ];
        $msgCiphertext = Mtool::depth_array_merge($msgCiphertext,$event);

        $requestData = [
            'method'        => 'chanpay.merchanttrade.weixin.jspay',
            'merchant_id'   => $this->config['merchant_id'],
            'product_code'  => $this->config['product_code'],
            'function_code' =>'1000120004',
            'format'        => $this->defaultConfig['format'],
            'charset'       =>  $this->defaultConfig['charset'],
            'sign_type'     =>$this->defaultConfig['sign_type'],
            'version'       => $this->defaultConfig['version'],
            'timestamp'     => $now,
            'biz_content'   => $this->getEncryptionRequestBody($msgCiphertext, $this->config['public_key']),
        ];
        $requestData['sign'] = $this->getSign($requestData, $this->config['private_key']);
        $requestRus = $this->post($this->URL['wx_pub'], $requestData);
        if($requestRus['code']!='00000'){
            $msg = $requestRus['msg']?$requestRus['msg']:($requestRus['sub_msg']?$requestRus['sub_msg']:'请求失败');
            throw new \Exception($msg);
        }
        if(isset($requestRus['sub_code'])&&$requestRus['sub_code']=='FAIL'){
            throw new \Exception($requestRus['sub_msg']);
        }
        $content = $requestRus['content'];
        if(!empty($content['pay_info'])){
            if(is_string($content['pay_info'])){
                $content['pay_info'] = Mtool::json_decode($content['pay_info']);
            }
        }
        return $content;
    }
}